package com.myx.servlet.admin.news;

import com.myx.pojo.News;
import com.myx.pojo.User;
import com.myx.service.news.NewsService;
import com.myx.service.news.NewsServiceImpl;
import com.myx.tool.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@WebServlet(name = "AddNewsServlet",value = "/AddNewsServlet")
public class AddNewsServlet extends HttpServlet {
    NewsService newsService=new NewsServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String categoryIdStr = request.getParameter("categoryId");
        Integer categoryId=null;
        if (categoryIdStr != null) {
            categoryId = Integer.parseInt(categoryIdStr);
        }
// 获取参数
        String newsTitle = request.getParameter("newsTitle");
        String newsSummary = request.getParameter("newsSummary");
        String newsContent = request.getParameter("newsContent");
        String imageUpload = request.getParameter("imageUpload");
        News news=new News();
        // 添加参数
        news.setCategoryId(categoryId);
        news.setTitle(newsTitle);
        news.setSummary(newsSummary);
        news.setContent(newsContent);
        news.setPicPath(imageUpload);
        HttpSession session = request.getSession();
        User adminUser = (User) session.getAttribute(Constant.LOGIN_SESSION);
        news.setCreateBy(adminUser.getId());
        news.setCreateDate(new Date());
        boolean isAdd= newsService.addNews(news);
        if (isAdd) {
            System.out.println("添加新闻功能执行成功");
            response.sendRedirect(request.getContextPath()+"/jsp/admin/news/index.jsp");
        }else {
            System.out.println("添加新闻功能执行失败");
            request.setAttribute(Constant.ADD_NEWS_FAIL,"添加新闻失败,请重新再试");
            request.getRequestDispatcher("/jsp/admin/news/newsAdd.jsp").forward(request,response);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
